# -*- coding: UTF-8 -*-

from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.properties import NumericProperty
from model.gamestate import Phase
from kivy.properties import StringProperty
from kivy.uix.popup import Popup


import model.gamestate

from ui.hat_widget import HatWidget


class ChangeNamePopup(Popup):
    def __init__(self, root, **kwargs):
        self.root = root
        self.player = None
        super(ChangeNamePopup, self).__init__(**kwargs)

    def change_text(self):
        name = self.name_input.text.strip()
        if self.player is not None:
            self.player.name = name
        was_same_name = False
        for player in self.root.game_state.players.players:
            if player.name == name:
                if not was_same_name:
                    was_same_name = True
                else:
                    self.ok_button.enabled = False
                    return
        self.ok_button.enabled = True

    def change_name(self):
        if not self.ok_button.enabled:
            return
        self.player.name = self.name_input.text.strip()
        self.root.player_explain = str(self.root.pair[0].idx + 1) + '. ' +\
            self.root.pair[0].name
        self.root.player_guess = str(self.root.pair[1].idx + 1) + '. ' +\
            self.root.pair[1].name
        self.dismiss()

    def on_open(self):
        self.name_input.text = self.player.name
        self.name_input.select_all()
        self.name_input.focus = True
        self.root.presenter.adapter.show_keyboard()

    def on_dismiss(self):
        self.name_input.focus = False
        self.root.presenter.adapter.hide_keyboard()


class FromToWidget(HatWidget):
    player_explain = StringProperty()
    player_guess = StringProperty()
    round_num = NumericProperty()

    def __init__(self, game_state, presenter, **kwargs):
        """ Construct FromTo screen
        need:
        valid gamestate.hat.words
        valid gamestate.game_round.player_pair or gamestate.game_round = None
        valid gamestate.players
        do:
        creates gamestate.game_round (if None)
        changes phase to BEFORE_ROUND
        Args:
        self.game_state: (GameState)
        presenter: (Presenter) main view presenter
        """
        self.game_state = game_state
        self.words_remaining = len(self.game_state.hat.words)
        self.presenter = presenter
        if self.game_state.rounds is None:
            self.game_state.rounds = []
        self.pair = [None, None]
        if self.game_state.players.players_select_strategy.is_pair_strategy():
            self.delete_butt_text = _('Remove current pair')
        else:
            self.delete_butt_text = _('Remove explaining player')

        self.change_name_popup = ChangeNamePopup(self)

        self.create_round()
        self.round_num = int(len(self.game_state.rounds) /
                             len(self.game_state.players.players)) + 1

        self.presenter.adapter.hide_keyboard()
        super(FromToWidget, self).__init__(**kwargs)

        self.redraw_delete_button()
        self.redraw_skip_button()

    def create_round(self):
        if (self.game_state.game_round is not None and
                self.game_state.game_round.time_left_sec <
                self.game_state.settings.time_per_round_sec):
            if (self.game_state.game_round.time_left_sec <= 0):
                self.presenter.change_phase(model.gamestate.Phase.GUESS_WORD)
            self.button_text = _('Resume')
            self.time_remaining = _('{} sec left'). \
                format(int(self.game_state.game_round.time_left_sec))
        else:
            self.time_remaining = ''
            self.button_text = _('Go!')
            self.game_state.game_round = \
                model.gamestate.GameRound(self.game_state.settings.
                                          time_per_round_sec,
                                          [], None,
                                          self.game_state.players.
                                          players_select_strategy.
                                          get_next_pair())
        self.pair = self.game_state.game_round.players_pair
        self.set_players_idx()
        self.player_explain = str(self.pair[0].idx + 1) + '. ' +\
            self.pair[0].name
        self.player_guess = str(self.pair[1].idx + 1) + '. ' +\
            self.pair[1].name

    def delete(self):
        self.delete_player(self.game_state.game_round.players_pair[0])
        if self.game_state.players.players_select_strategy.is_pair_strategy():
            self.delete_player(self.game_state.game_round.players_pair[1])

        self.game_state.players.players_select_strategy.is_players_deleted =\
            True

        self.skip()
        self.redraw_delete_button()

    def delete_player(self, player):
        for i in range(len(self.game_state.players.players)):
            if self.game_state.players.players[i] == player:
                del (self.game_state.players.players[i])
                return
        self.redraw_delete_button()

    def finish(self, finish=False):
        """ changes phase to BEFORE_ROUND
        call on release 'Старт' button
        """
        self.game_state.is_paused = False

        next_phase = Phase.CURRES if finish else Phase.BEFORE_ROUND
        self.presenter.change_phase(next_phase)

    def open_popup(self, player):
        self.change_name_popup.player = player
        self.change_name_popup.open()

    def prev_view(self):
        self.presenter.change_phase(model.gamestate.Phase.PLAYERS_ORDER)

    def redraw_delete_button(self):
        self.delete_button.enabled =\
            (len(self.game_state.players.players) > 2 and
             self.presenter.settings.game.may_delete_player)

    def redraw_skip_button(self):
        self.skip_button.enabled = self.presenter.settings.game.may_skip_turn

    def set_players_idx(self):
        idx = 0
        for player in self.game_state.players.players:
            player.idx = idx
            idx += 1

    def skip(self):
        self.game_state.rounds.append(self.game_state.game_round)
        self.round_num = int((len(self.game_state.rounds)) /
                             len(self.game_state.players.players)) + 1
        self.game_state.game_round = None
        self.create_round()

    def update(self):
        self.redraw_delete_button()
        self.redraw_skip_button()


class FromToApp(App):
    def build(self):
        return


if __name__ == '__main__':
    FromToApp().run()
